package com.west.xu.auth.utils;

import com.tencent.tsf.gateway.core.constant.AlgType;
import com.tencent.tsf.gateway.core.exception.UnsupportedException;
import com.tencent.tsf.gateway.core.util.SignUtil;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.HmacUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class AuthGenerate {
    static Logger logger = LoggerFactory.getLogger(AuthGenerate.class);

    /**
     * 生成签名
     *
     * @param nonce     随机字符串
     * @param secretId  密钥 ID
     * @param secretKey 密钥值
     * @param algType   签名算法 {@link AlgType}
     */
    public static String generate(String nonce, String secretId, String secretKey, AlgType algType) {
        String digestValue = nonce + secretId + secretKey;
        byte[] serverSignBytes;
        switch (algType) {
            case HMAC_MD5:
                serverSignBytes = HmacUtils.hmacMd5(secretKey, digestValue);
                break;
            case HMAC_SHA_1:
                serverSignBytes = HmacUtils.hmacSha1(secretKey, digestValue);
                break;
            case HMAC_SHA_256:
                serverSignBytes = HmacUtils.hmacSha256(secretKey, digestValue);
                break;
            case HMAC_SHA_512:
                serverSignBytes = HmacUtils.hmacSha512(secretKey, digestValue);
                break;
            default:
                throw new UnsupportedException("不支持的鉴权算法: " + algType);
        }
        String signValue = Base64.encodeBase64String(serverSignBytes);
        if (logger.isDebugEnabled()) {
            logger.debug("签名明文：{}，签名密文：{}", digestValue, signValue);
        }
        return signValue;
    }

    public static void main(String[] args) {
        String secretId = "PcXhaXogQtetKyj3zOqlQw==";
        String secretKey = "a3l7P4z7yS4p1tbBXSO2oA==";
        String nonce = "D7pAR5fqXXXXx1yacuVzdO";
        AlgType algType = AlgType.HMAC_SHA_1;
        System.out.println(SignUtil.generate(nonce, secretId, secretKey, algType));
    }
}
